'''
Created on Aug 24, 2010

@author: alia
'''
import logging
log = logging.getLogger('audio')

import pyglet.media
import data
import config

class Audio(object):
    def __init__(self):
        
        log.info("initialising audio")
                 
        self.player = pyglet.media.Player()
        self.sounds = {}
        self.sfx_volume = config.sfxvolume/10.0
        
    def load_sound(self, name):
        
        log.info("loading sound:"+str(name))
                 
        if name not in self.sounds:
            self.sounds[name] = data.load_sound(name)
        return self.sounds[name]

    def play_sound(self, name):
        if name not in self.sounds:
            self.load_sound(name)  
        
        log.info("playing sound:"+str(name))
                 
        self.sounds[name].play().volume = self.sfx_volume

    def play_song(self, name):
        
        log.info("playing song:"+str(name))
                 
        self.player.volume = config.musicvolume/10.0
        self.player.queue(data.load_song(name))
        self.player.play()
        self.player.eos_action = 'loop'

    def next_song(self):       
        log.info("stopping music:")
        self.player.next()

    def sound_volume(self, vol):       
        log.info("setting sound volume:"+str(vol))
                 
        self.sfx_volume = vol 
    def music_volume(self, vol):       
        log.info("setting music volume:"+str(vol))
                 
        self.player.volume = vol
    def pause_music(self):
        log.info("pausing music")
                 
        self.music.play()
    def start_music(self):        
        log.info("starting music")
                 
        self.music.play()
    def pre_load_sfx(self, sfx_list):
        log.info("pre-caching sound effects: "+str(sfx_list))
                 
        for sfx in sfx_list:
            self.load_sound(sfx)  
                 
_audio = None

def init_audio():
    global _audio
    
    if _audio is None:
        _audio = Audio()

def play_sound(name):
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.play_sound(name)
    
def sound_volume(vol):
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.sound_volume(vol)

def play_song(name):
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.play_song(name)

def next_song():
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.next_song()

def music_volume(vol):
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.music_volume(vol)
    
def pre_load_sfx(sfx_list):
    global _audio

    if _audio is None:
        init_audio()
    
    _audio.pre_load_sfx(sfx_list)
    
    